package uno.rocc.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import uno.rocc.system.domain.dao.SysPermission;
import uno.rocc.system.domain.dao.SysUser;
import uno.rocc.system.domain.dao.SysUserPermission;
import uno.rocc.system.domain.dto.SysUserQueryParam;
import uno.rocc.system.domain.vo.SysUserVo;
import uno.rocc.system.mapper.SysUserMapper;
import uno.rocc.system.service.SysPermissionService;
import uno.rocc.system.service.SysUserPermissionService;
import uno.rocc.system.service.SysUserService;

import java.io.Serializable;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final SysUserPermissionService sysUserPermissionService;
    private final SysPermissionService sysPermissionService;

    @Override
    public SysUser getById(Serializable id) {
        SysUser sysUser = super.getById(id);
        sysUser.setPassword("");
        return sysUser;
    }

    @Override
    public Page<SysUserVo> list(Page<SysUser> page, SysUserQueryParam params) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();

        //查询用户名
        addConditionLike(query, SysUser::getUsername, params.getUsername());
        //查询状态
        addConditionEq(query, SysUser::getStatus, params.getStatus());
        page(page, query);

        //拷贝分页数据
        Page<SysUserVo> rlt = new Page<SysUserVo>();
        BeanUtil.copyProperties(page, rlt);
        return rlt;
    }

    @Override
    public List<String> getPermissionAllById(Integer sysUserId) {

        List<Object> list = sysUserPermissionService.listObjs(
                new LambdaQueryWrapper<SysUserPermission>()
                        .select(SysUserPermission::getPermissionId) //只选择查询权限id
                        .eq(SysUserPermission::getUserId, sysUserId)    //查询当前用户id
        );
        if (ObjectUtil.isEmpty(list)) {
            return null;
        }
        return sysPermissionService.listObjs(new LambdaQueryWrapper<SysPermission>()
                        .select(SysPermission::getPermission)
                        .in(SysPermission::getId, list)
                , Object::toString);
    }
}
